package cn.com.kh;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.kh
 * @className: LogAnalyticAPICost
 * @author: LiJT
 * @description: TODO
 * @date: 2023-07-17 18:05
 * @version: 1.0
 */
public class LogAnalyticAPICost {
    private static final Logger log = LoggerFactory.getLogger(LogAnalyticAPICost.class);
    private static final List<List<String>> resUsers = new ArrayList<>();
    private static final String regInfo_Start = "] method:/";
    private static final String regInfo_End = "] result:";
    private static final int costTimeMin = 1000;

    private static final String[] skipKeys = "webchat".split(";");

    public static void main(String[] args) throws Exception {

        // 日志文件路径
        String logDir = "C:\\Users\\lijun\\Desktop\\49logs\\1111.log";
        log.debug("日志文件路径:" + logDir);

        List<String> fileList = ReadFile("C:\\Users\\lijun\\Desktop\\49logs");
        log.debug("日志路径文件:" + fileList.toString());

        for (String logPath : fileList) {
            loadFileDeal(logPath);
        }

    }

    private static List<String> ReadFile(String fileDir) {
        List<String> fileList = new ArrayList<String>();
        File file = new File(fileDir);
        File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
        if (files == null) {// 如果目录为空，直接退出
            return fileList;
        }
        // 遍历，目录下的所有文件
        for (File f : files) {
            if (f.isFile()) {
                fileList.add(f.getPath().toString());
            } else if (f.isDirectory()) {
                System.out.println(f.getAbsolutePath());
                ReadFile(f.getAbsolutePath());
            }
        }
        return fileList;
    }

    public static void loadFileDeal(String logDir) {
        resUsers.clear();

        // 读取日志 - 调用时间 方法 结束时间 耗时
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(logDir))) {
            String line;
            Pattern p_Start = Pattern.compile(regInfo_Start);
            Pattern p_End = Pattern.compile(regInfo_End);
            while ((line = bufferedReader.readLine()) != null) {
                // 处理每一行数据 .....
                Matcher m_Start = p_Start.matcher(line);
                Matcher m_End = p_End.matcher(line);

                boolean b_Start = m_Start.find();
                boolean b_End = m_End.find();
                if (b_Start || b_End) {
                    // log.debug("处理每一行数据 b_Start:" + b_Start + " b_End:" + b_End);
                    if (b_Start) {
                        // 开始行
                        List<String> hisLog = new ArrayList<>();
                        String startTime = line.substring(0, line.indexOf("["));
                        String threadKey = line.substring(line.indexOf("[", line.indexOf("[") + 1) + 1, line.indexOf("]", line.indexOf("]") + 1));
                        String appKey = line.substring(line.indexOf("method:/") + 8);
                        // log.debug("开始行 数据:" + startTime + " threadKey:" + threadKey + " appKey:" + appKey);

                        if (!Arrays.asList(skipKeys).contains(appKey)) {
                            hisLog.add(startTime);
                            hisLog.add(threadKey);
                            hisLog.add(appKey);

                            resUsers.add(hisLog);
                        }

                    } else {
                            String endTime = line.substring(0, line.indexOf("["));
                            String threadKey = line.substring(line.indexOf("[", line.indexOf("[") + 1) + 1, line.indexOf("]", line.indexOf("]") + 1));
                            // log.debug("结束行 数据:" + endTime + " threadKey:" + threadKey);

                            addLogEnd(resUsers, threadKey, endTime);

                    }
                }
            }

            if (resUsers.size()>0) {
                log.debug("[⛔]" + logDir);
            }else {
                log.debug("[☣]" + logDir);
            }
            printList(resUsers, costTimeMin);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void addLogEnd(List<List<String>> resUsers, String threadKey, String endTime) {
        try {
            int listNum = resUsers.size() - 1;
            for (int i = listNum; i >= 0; i--) {
                List<String> lineList = resUsers.get(i);
                if (lineList.get(1).equals(threadKey) && lineList.size() <= 3) {
                    lineList.add(endTime);
                    resUsers.set(i, lineList);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    // 获取两个时间相差毫秒
    public static long getMills(String oldTime, String newTime) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long diff = 0;
        try {
            long NTime = df.parse(newTime).getTime();
            //从对象中拿到时间
            long OTime = df.parse(oldTime).getTime();
            diff = (NTime - OTime) + 1;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return diff;
    }


    public static void printList(List<List<String>> resUsers, int costTimeMin) {
        try {
            int listNum = resUsers.size();
            for (int i = 0; i < listNum; i++) {
                if (costTimeMin <= getMills(resUsers.get(i).get(0), resUsers.get(i).get(3))) {
                    log.debug("结果行-" + resUsers.get(i) + " 耗时:" + getMills(resUsers.get(i).get(0), resUsers.get(i).get(3)));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

}
